import tip from '@/utils/tip'

// 检查权限=>跳授权setting
function checkScope(scopeName) {
    setting(scopeName).then(res => {
        if (!res.authSetting[scopeName]) {
            rejectNav()
            return false
        } else {
            return true
        }
    })
}
// 查看用户设备权限
const setting = async () => {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success(res) {
                resolve(res)
            }
        });
    })
}
const rejectNav = () => {
    wx.navigateTo({
        url: '/pages/openSetting'
    })
}





const pay = async (obj) => {
    return new Promise(function(resolve, reject) {
        wx.requestPayment({
            timeStamp: obj.timestamp,
            nonceStr: obj.nonceStr,
            package: obj.package,
            signType: obj.signType || 'MD5',
            paySign: obj.paySign,
            success(res) {
                resolve(res)
            },
            fail(err) {
                resolve(false)
                console.log('requestPayment_fail:', err)
                tip.error('支付失败')
            },
        })
    })
}

// 设备型号 判断IPX
const systemInfoJudgeIpx = async () => {
    return new Promise(function(resolve, reject) {
        wx.getSystemInfo({
            success: function(res) {
                var model = res.model
                if (model.search('iPhone X') != -1) {
                    resolve(true)
                } else {
                    resolve(false)
                }
            }
        })
    })
}

// 终端信息
const systemInfo = async () => {
    return new Promise(function(resolve, reject) {
        wx.getSystemInfo({
            success(res) {
                resolve(res)
            }
        })
    })
}


// 跳转小程序 (需要配置文件注册navigateToMiniProgramAppIdList)
const navigateToOtherMiniProgram = async (appId, path = '', extraData = {}) => {
    return new Promise(function(resolve, reject) {
        wx.navigateToMiniProgram({
            appId,
            path,
            extraData,
            envVersion: 'develop', //develop 开发版,trial 体验版,release	正式版
            success(res) {
                resolve(res)
            },
            fail(err) {
                resolve(false)
                console.log('navigateToMiniProgram_fail:', err)
            }
        })
    })
}


// 登录
const login = async () => {
    return new Promise(function(resolve, reject) {
        wx.login({
            success(res) {
                if (res.code) {
                    resolve(res.code)
                }
            },
            fail(err) {
                tip.error('网络错误，请稍后重试')
                resolve(false)
                console.log('login_fail:', err)
            }
        })
    })
}


// 检查session
const checkSession = async () => {
    return new Promise(function(resolve, reject) {
        wx.checkSession({
            success(res) {
                resolve(true)
            },
            fail(err) {
                resolve(false)
                console.log('checkSession_fail:', err)
            }
        })
    })
}


// 用户信息
const userInfo = async () => {
    const scopeName = 'scope.userInfo'
    return new Promise(function(resolve, reject) {
        wx.getUserInfo({
            success(res) {
                resolve(res)
            },
            fail(err) {
                checkScope(scopeName)
                resolve(false)
                console.log('getuserinfo_fail:', err)
            }
        })
    })
}

// 微信步数
const runData = async () => {
    const scopeName = 'scope.werun	'
    return new Promise(function(resolve, reject) {
        wx.getWeRunData({
            success(res) {
                resolve(res)
            },
            fail(err) {
                checkScope(scopeName)
                resolve(false)
                console.log('getWeRunData_fail:', err)
            }
        })
    })

}

// 拨号
const phoneCall = async (phone) => {
    return new Promise(function(resolve, reject) {
        wx.makePhoneCall({
            phoneNumber: phone,
            success(res) {
                resolve(true)
            },
            fail(err) {
                resolve(false)
                console.log('makePhoneCall_fail:', err)
            }
        })
    })
}

// 下载
const downLoad = async (url) => {
    const scopeName = 'scope.writePhotosAlbum'
    tip.loading('保存中')
    return new Promise(function(resolve, reject) {
        wx.downloadFile({
            url: url,
            success(down_res) {
                if (down_res.statusCode === 200) {
                    // 保存图片
                    wx.saveImageToPhotosAlbum({
                        filePath: down_res.tempFilePath,
                        success(res) {
                            tip.success('保存成功')
                            resolve(res)
                        },
                        fail(err) {
                            tip.error('保存失败')
                            checkScope(scopeName)
                            resolve(false)
                            console.log('saveImageToPhotosAlbum_fail:', err)
                        },
                    })
                }
            },
            fail(err) {
                tip.error('下载失败')
                resolve(false)
                console.log('downloadFile:', err)
            }
        })
    })
}

// 选择照片
const chooseImage = async (max_size = 2000000) => {
    return new Promise(function(resolve, reject) {
        wx.chooseImage({
            sizeType: ['compressed'], //可选择原图或压缩后的图片
            sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
            success(res) {
                let tempFilesSize = res.tempFiles[0].size; //获取图片的大小，单位B
                if (tempFilesSize <= max_size) {
                    resolve(res.tempFilePaths)
                } else {
                    tip.alert('图片大于2M');
                    resolve(false)
                }
            },
            fail(err) {
                console.log('chooseImage_fail:', err)
                resolve(false)
            }
        })
    })
}




// 上传
const upload = async (url, path, name = "", data = {}) => {
    tip.loading('图片上传中')
    return new Promise(function(resolve, reject) {
        wx.uploadFile({
            url: url,
            filePath: path,
            name: name,
            header: {
                "Content-Type": "multipart/form-data"
            },
            formData: data,
            success(res) {
                resolve(res)
            },
            fail(err) {
                tip.error('上传失败')
                reject(err)
                console.log('uploadFile_fail:', err)
            },
            complete() {
                tip.loaded()
            }
        })
    })
}


// 剪贴板的内容
const clipboard = async (data, toast = true) => {
    return new Promise(function(resolve, reject) {
        wx.setClipboardData({
            data: data,
            success(res) {
                toast ? wx.hideToast() : ""
                wx.getClipboardData({
                    success(res) {
                        toast ? wx.hideToast() : ""
                        resolve(res.data)
                    }
                })
            }
        })
    })
}


//获取当前的地理位置
const Location = async (openSetting = true, type = 'wgs84') => {
    const scopeName = 'scope.userLocation'
    return new Promise(function(resolve, reject) {
        wx.getLocation({
            type,
            success(res) {
                resolve({ latitude: res.latitude, longitude: res.longitude })
            },
            fail(err) {
                openSetting ? checkScope(scopeName) : ''
                reject()
                console.log('getLocation_fail:', err)
            }
        })
    })
}
// 搜索位置
const ChooseLocation = async () => {
    const scopeName = 'scope.userLocation'
    return new Promise(function(resolve) {
        wx.chooseLocation({
            success(res) {
                resolve(res)
            },
            fail(err) {
                checkScope(scopeName)
                resolve(false)
                console.log('chooseLocation_fail:', err)
            }
        })
    })
}




export default {
    systemInfoJudgeIpx,
    systemInfo,
    navigateToOtherMiniProgram,
    pay,
    login,
    checkSession,
    userInfo,
    runData,
    phoneCall,
    downLoad,
    chooseImage,
    upload,
    clipboard,
    Location,
    ChooseLocation,
    setting
}